package com.library.uiframework.widget.imageview;

import java.lang.ref.WeakReference;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;

/**
 * Created by brucelee on 3/1/16.
 */
class MaskTask extends AsyncTask<Object, Void, Bitmap> {
    private Bitmap mBitmap;
    private WeakReference<NetworkImageView> mNetworkImageViewWeakReference;
    private Bitmap mMaskBitmap;
    private PorterDuff.Mode mMode;

    public void onDestory(){
        cancel(true);
//        if (mBitmap != null) {
//            mBitmap.recycle();
//            mBitmap = null;
//        }
//
//        if(mMaskBitmap != null){
//            mMaskBitmap.recycle();
//            mMaskBitmap = null;
//        }
    }

    public MaskTask(Bitmap bitmap, NetworkImageView networkImageView, Bitmap maskBitMap, PorterDuff.Mode mode) {
        mBitmap = bitmap;
        mNetworkImageViewWeakReference = new WeakReference<NetworkImageView>(networkImageView);
        mMaskBitmap = maskBitMap;
        mMode = mode;
    }

    @Override
    protected Bitmap doInBackground(Object... params) {
        try {
            return maskBitmap(mBitmap, mMaskBitmap, PorterDuff.Mode.DST_IN);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
        if(bitmap == null){
            return;
        }
        NetworkImageView networkImageView = mNetworkImageViewWeakReference.get();
        if (networkImageView != null) {
            networkImageView.superSetImageDrawable(getDrawable(bitmap));
        }

    }

    protected Drawable getDrawable(Bitmap bitmap) {
        return new RoundedDrawable(bitmap);
    }

    public static Bitmap maskBitmap(Bitmap disBitmap, Bitmap srcBitmap, PorterDuff.Mode mode){
        /**
         * 主要代码实现
         */
        //获取图片的资源文件
        Bitmap original = disBitmap;
        //获取遮罩层图片
        Bitmap mask = srcBitmap;
        Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(), Bitmap.Config.ARGB_8888);
        //将遮罩层的图片放到画布中
        Canvas mCanvas = new Canvas(result);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setXfermode(new PorterDuffXfermode(mode));
        Rect src = new Rect(0, 0, mask.getWidth(), mask.getHeight());
        Rect disRect = new Rect(0, 0, original.getWidth(), original.getHeight());
        mCanvas.drawBitmap(original, disRect, src, null);
        mCanvas.drawBitmap(mask, 0, 0, paint);
        paint.setXfermode(null);
        return result;
    }
}
